class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
    }
    // 得到主表数据
    GetEntityData() {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['gradedBy'] = $.trim($("#UserId").val());      // 单耗员
        item['icLabDipIndication'] = formatNullInputValue($.trim($("#IcLabDipIndication").val()));          // IC色样
        item['embroideryLaceAndOther'] = formatNullInputValue($.trim($("#EmbroideryLaceAndOther").val()));  // 刺绣

        return item;
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        $("#CatalogueId").val(item.catalogueId);
        $("#ProductId").val(formatNullData(item.productId));
        $("#StyleNo").val(item.styleNo);
        $("#ProductName").val(item.productName);
        $("#CustomerName").val(item.customerName);
        $("#DateOfFilling").val(item.dateOfFilling);
        $("#DesignedBy").val(item.designedBy);
        $("#DesignedByName").val(item.designedByName);
        $("#GradedBy").val(item.gradedBy);
        $("#GradedByName").val(item.gradedByName);
        $("#IcLabDipIndication").val(item.icLabDipIndication);
        $("#EmbroideryLaceAndOther").val(item.embroideryLaceAndOther);
        $("#Notes").val(item.notes);
        $("#UpdatedByName").val(item.updatedByName);
        $("#UpdatedDate").val(formatNullData(item.updatedDate));
        $("#Description").val(item.description);
        $("#MrpStatus").val(item.mrpStatus);           // 调达表审核状态
        $("#QuotedFlag").val(item.quotedFlag);         // 是否被引用

        // 得到相关配色方案用成品色
        _InstancePageLines.productColourNode = data.ProductColourNode;
        // 得到相关成品尺码
        _InstancePageLines.productSizeNode = data.ProductSizeNode;
        //重建明细表头
        _InstancePageLines.BuildDataTableHeader();
        // 显示明细数据
        _InstancePageLines.BuildDataTable(data.LinesList);

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;
        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
        $("#StyleNo").focus();
    }
    Save() {
        super.DoAjax(this.GetEntityData(), "/tech/piece_yardage_onesize/header/updateGrading.html", () => {
            $("#GradedBy").val($("#UserId").val());
            $("#GradedByName").val($("#UserName").val());
            ShowSuccessMessagePanel("保存成功。");
        });
    }
    Expand() {
        super.Expand(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
    /* 折叠 */
    Collapse() {
        super.Collapse(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
        $("#remark").show();
    }
    HidePageElement() {
        //$("Button.act__save").hide();
        //$("span.act__delete").removeClass("trash");
        //$("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
        //$("#remark").hide();
    }
}

class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.$input = null;
        this.productColourNode = [];
        this.ProductSizeNode = [];
    }
    BuildDataTableHeader() {
        // 形成颜色表头 
        let _th = '';
        let _colWidth = 0;
        let _col = '';
        if ((this.productSizeNode !== null) && (this.productSizeNode.length > 0)) {
            for (let i = 0; i < this.productSizeNode.length; i++) {
                _col += '<col style="width:70px;" />';
                _th += '<th class="edit__column">' + this.productSizeNode[i].productSizeName + '</th>';
                _colWidth += 70;
            }
        }
        if ((this.productColourNode !== null) && (this.productColourNode.length > 0)) {
            for (let i = 0; i < this.productColourNode.length; i++) {
                _col += '<col style="width:130px;" />';
                _th += '<th>' + this.productColourNode[i].productColourName + '</th>';
                _colWidth += 130;
            }
        }
        _col += '<col style="width:65px;" />';
        _th += '<th style="text-align:center;">备料来源</th>';
        _colWidth += 65;
        let w = $(window).width() - 802 - 16 - 17;
        let _w_desc = (w - _colWidth) < 400 ? 400 : (w - _colWidth);
        _col += '<col style="' + _w_desc + 'px;" />';
        _th += '<th>备注</th>';
        _colWidth += _w_desc;
        $("#tabHeader12").css({width: _colWidth});
        $("#tabData12").css({width: _colWidth});
        $("#tabHeader12 thead tr").empty();
        $("#tabHeader12 colgroup").empty();
        $("#tabData12 colgroup").empty();
        $("#tabHeader12 colgroup").html(_col);
        $("#tabData12 colgroup").html(_col);
        $("#tabHeader12 thead tr").html(_th);
    }
    BuildDataTable(result) {
        $('#tabData11 tbody').empty();
        $('#tabData12 tbody').empty();
        // 得到数据列表
        if (result === null || result.length === 0) {
            $('#loading').hide();
            this.rows = 0;
            // 自适应高度
            this.AutoAdjustTableHeightForLines();
            return false;
        }
        let content01 = '';
        let content02 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            if (result[i].quotedFlag === true) {
                content01 += '<tr _mash_quoted="1" style="background-color:#606060; color:#fff;" _mash_id="' + id + '" _materialId="' + result[i].materialId + '">';
                content01 += '<td></td>';
                content01 += '<td style="text-align:center;">' + formatNullData(result[i].orderNo) + '</td>';
            } else {
                content01 += '<tr _mash_quoted="0" _mash_id="' + id + '" _mash_material_id="' + result[i].materialId + '">';
                content01 += '<td><label style="margin-left:3px;" class="btn" for="R-' + id + '"><input id="R-' + id + '" name="_check_row" type="checkbox" onclick="_InstancePageLines.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + id + '"/><i></i><span></span></label></td>';
                content01 += '<td style="text-align:center;">' + formatNullData(result[i].orderNo) + '</td>';
            }
            content01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
            content01 += '<td>' + formatNullData(result[i].supplierName) + '</td>';
            content01 += '<td class="edited-cell">' + formatNullData(result[i].partOfNeed) + '</td>';
            if (result[i].quotedFlag === false) {
                content01 += '<td class="edited-cell">' + formatNullData(result[i].materialCode) + '</td>';
            } else {
                content01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
            }
            content01 += '<td>' + formatNullData(result[i].specification) + '</td>';
            content01 += '<td style="text-align:center;" _mash_uom_id="' + result[i].uomId + '">' + formatNullData(result[i].uomName) + '</td>';
            content01 += '</tr>';

            if (result[i].quotedFlag === true) {
                content02 += '<tr style="background-color:#606060; color:#fff;">';
            } else {
                content02 += '<tr>';
            }
            if (result[i].quotedFlag === false) {
                if (this.productSizeNode !== null) {
                    for (let j = 0; j < this.productSizeNode.length; j++) {
                        let _productSizeId = this.productSizeNode[j].productSizeId.toString();
                        let _t = false;
                        $.each(result[i].sizeGrade, function (index, data) {
                            if (data.ProductSizeId === _productSizeId) {
                                let _PieceYardage = data.PieceYardage === "0" ? null : parseFloat(data.PieceYardage);
                                content02 += '<td class="edited-cell">' + formatNullData(_PieceYardage) + '</td>'; // 对应尺码的单耗
                                _t = true;
                                return false;
                            }
                        });
                        if (_t === false)
                            content02 += '<td class="edited-cell"></td>'; // 对应尺码的单耗
                    }
                }
            } else {
                if (this.productSizeNode !== null) {
                    for (let j = 0; j < this.productSizeNode.length; j++) {
                        let _productSizeId = this.productSizeNode[j].productSizeId.toString();
                        let _t = false;
                        $.each(result[i].sizeGrade, function (index, data) {
                            if (data.ProductSizeId === _productSizeId) {
                                let _PieceYardage = data.PieceYardage === "0" ? null : parseFloat(data.PieceYardage);
                                content02 += '<td>' + formatNullData(_PieceYardage) + '</td>'; // 对应尺码的单耗
                                _t = true;
                                return false;
                            }
                        });
                        if (_t === false)
                            content02 += '<td></td>'; // 对应尺码的单耗
                    }
                }
            }
            // 显示颜色搭配情况
            if (this.productColourNode !== null) {
                for (let j = 0; j < this.productColourNode.length; j++) {
                    let _productColourId = this.productColourNode[j].productColourId.toString();
                    let _t = false;
                    $.each(result[i].colourSchema, function (index, data) {
                        if (data.ProductColourId === _productColourId) {
                            content02 += '<td>' + formatNullData(data.MaterialColour) + '</td>'; // 搭配的材料色
                            _t = true;
                            return false;
                        }
                    });
                    if (_t === false)
                        content02 += '<td></td>'; // 搭配的材料色
                }
            }
            content02 += '<td style="text-align:center;" _mash_type_id="' + result[i].materialPreparedTypeId + '">' + formatNullData(result[i].materialPreparedTypeName) + '</td>';    // 物料来源
            content02 += '<td>' + formatNullData(result[i].description) + '</td>';                 // 备注
            content02 += '</tr>';
            $('#tabData11 tbody').append(content01);
            $('#tabData12 tbody').append(content02);
            content01 = '';
            content02 = '';

        }
        setTwoTableRowColor("tabData11", "tabData12");
        $("#CheckAll").prop("checked", false);

        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();

        let cell_id = "_cell__field";
        let cell_name = "__cell__field";
        $('#tabData12 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), cell_id, cell_name, 0);
        });

        $("#loading").hide();
    }
    // 得到要保存的数据
    GetLinesData() {
        let _this = this;
        let linesData = [];
        // 得到修改过数据
        $('#tabData12 tbody').find("tr").each(function (index) {
            let $tr2 = $(this);
            let $tr1 = $('#tabData11 tbody').find("tr").eq(index);
            if ($tr2.find("td.dirty").length) {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = $tr1.attr("_mash_id");
                item['updatedBy'] = $("#UserId").val();
                // 取得尺码单耗
                let _sizeGradeList = [];
                for (let j = 0; j < _this.productSizeNode.length; j++) {
                    let _item = {};
                    if ($.trim($tr2.find('td').eq(j).text()) !== "") {
                        _item['headerId'] = $("#HeaderId").val();
                        _item['parentLinesId'] = $tr1.attr("_mash_id");
                        _item['productSizeId'] = parseInt(_this.productSizeNode[j].productSizeId);
                        _item['pieceYardage'] = formatNullInputValue($.trim($tr2.find('td').eq(j).text()));
                        _sizeGradeList.push(_item);
                    }
                }
                item['sizeGradeList'] = _sizeGradeList;
                linesData.push(item);
            }
        });
        return linesData;
    }
    SaveLines() {
        //step 1、进行页面验证，失败则返回
        let success_01 = CheckGridInput();
        if (!success_01)
            return;

        super.DoAjax(this.GetLinesData(), "/tech/piece_yardage_lines/sizegrade/update.html", (data, _this) => {
            $("#GradedBy").val($("#UserId").val());
            $("#GradedByName").val($("#UserName").val());
            if (data.Success === undefined) {
                ShowSuccessMessagePanel("保存成功。");
            } else {
                if (data.Success) {
                    // 刷新明细
                    _this.BuildDataTable(data.LinesList);
                    ShowSuccessMessagePanel("保存成功。");
                    // 更新单耗员
                    $("#gradedBy").val($("#UserId").val());
                    $("#gradedByName").val($("#UserName").val());
                }
            }
        });
    }
    // 批量选择的数据(类中data:this.GetCheckedLinesData)
    GetCheckedLinesData() {
        let choiced_data = [];
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = $(this).parent().parent().parent().attr("_mash_id");
                item['updatedBy'] = $.trim($("#UserId").val());
                choiced_data.push(item);
            });
        }
        return choiced_data;
    }
    // 批量清空用量
    DoClearPieceYardage() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            showModal(400, 140, '确认', '', null, null, 1, '请问，确定要清空所选材料单用量吗？', () => {
                this.OnClearPieceYardage();
            }, () => {
                return false;
            });
        } else {
            ShowErrorMessagePanel("请选择要清空的材料数据。");
            return false;
        }
    }
    OnClearPieceYardage() {
        super.DoAjax(this.GetCheckedLinesData(), "/tech/piece_yardage_lines/sizegrade/clear.html", (data, _this) => {
            $("#GradedBy").val($("#UserId").val());
            $("#GradedByName").val($("#UserName").val());
            // 刷新明细
            _this.BuildDataTable(data);
            ShowSuccessMessagePanel("清空所选材料单用量成功。。");
        });
    }
    // 编辑搭配用成品色
    EditProductSize() {
        showModal(495, 538, '编辑成品尺码', parent.basePath + '/tech/piece_yardage_lines/product_size/edit.html', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            // 清空选择的数据
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    // 弹出颜色的选择窗口
    DoChoiceSize($input) {
        this.$input = $input;
        let _choice = new CommonChoice();
        _choice.DoChoiceSize(0, (data) => {
            if (data === false) {
                this.$input.focus();
            } else {
                this.$input.parent().attr("_mash_colour_id", data[0]);
                this.$input.val(data[2]);   // 色号
                this.$input.focus();
            }
        });
    }
    // 同步填写当前行其他尺码单用量
    SyncRowsData() {
        if ($('#tabData12 tbody tr.row__clicked').length) {
            let $row = $('#tabData12 tbody tr.row__clicked');
            let _pieceYardage = "";
            if ($row.find("td.dirty").length) {
                _pieceYardage = $.trim($row.find("td.dirty").eq(0).text());
            } else {
                _pieceYardage = $.trim($row.find('td').eq(0).text());
            }
            for (let j = 0; j < this.productSizeNode.length; j++) {
                $row.find('td').eq(j).text(_pieceYardage);
                $row.find('td').eq(j).addClass("dirty");
            }
        } else {
            ShowErrorMessagePanel("请选择要同步单用量的材料。");
        }
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, function ($row, index) {
            $('#tabData12 tbody tr:eq(' + index + ')').addClass("row__selected");
            // 设置删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
        }, function ($row, index) {
            $('#tabData12 tbody tr:eq(' + index + ')').removeClass("row__selected");
            // 设置删除按钮有效
            let _event_delete_onclick = '_InstancePageLines.DeleteLines($(this))';
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_delete_onclick);
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = $("#divH11").offset().top + 26;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        let _rc = Math.floor((h - _tabTop - 25) / 25);
        let _dh = _rc * 25 + 17;
        let _rowH = this.rows * 25 + 17; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD11").css({"max-height": _dh - 17, height: _dh - 17});
        $("#divD12").css({"max-height": _dh + 1, height: _dh + 1});
    }
    ScrollTo() {
        $('#divH12').scrollLeft($('#divD12').scrollLeft());
        $('#divD11').scrollTop($('#divD12').scrollTop());
    }
}

var _InstancePageHeader = null;
var _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();

    let piece_yardage_fullsize_grading_list_result = $.cookie("piece_yardage_fullsize_grading_list_result") === undefined ? "" : $.cookie("piece_yardage_fullsize_grading_list_result");
    let _pageListData = [];
    if (piece_yardage_fullsize_grading_list_result !== "") {
        _pageListData = piece_yardage_fullsize_grading_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }
    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/tech/piece_yardage_fullsize/grading/list.html",
            "/tech/piece_yardage_onesize/fetchByKey.html",
            null, null, null);

    _InstancePageLines = new MyPageLines();
    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelData"});

    $("#hPanelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-up")) {
            _InstancePageHeader.Collapse();
        } else {
            _InstancePageHeader.Expand();
        }
    });

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let wLeftList = 802; //左边列表固定宽度
    let w = $(window).width();

    $("#divH12").css({width: w - 16 - wLeftList - 17});
    $("#divD12").css({left: -1, width: w - wLeftList - 15});

    if (_InstancePageLines !== null)
        _InstancePageLines.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
function CheckGridInput() {
    $('#tabData12 tbody').find("tr").each(function (index) {
        for (let i = 0; i < _InstancePageLines.productSizeNode.length; i++) {
            let _quantity = $.trim($(this).find('td').eq(i).text()).length > 0 ? $.trim($(this).find('td').eq(i).text()) : 0; // 单耗

            if (_quantity !== 0) {
                if (!isNumber(_quantity)) {
                    GridCheckErrHandle($(this), i, '请输入正确的数字！');
                } else {
                    GridCheckSuccessHandle($(this), i);
                }
            } else {
                GridCheckSuccessHandle($(this), i);
            }
        }
    });
    if ($('#tabData12 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}